

//
//  EmoticonCollectionViewCell.swift
//  自定义表情键盘
//
//  Created by YYY on 2017/9/6.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

//表情cell被选中的协议方法
@objc protocol EmoticonCellSelectedDelegate: NSObjectProtocol
{
    
    /// 表情cell被选中
    ///
    /// - Parameter emoticonModel: 表情模型model，如果是nil，表示是删除按钮
    func emoticonCellDidSelected(cell: EmoticonCollectionViewCell,emoticonModel: CPJEmoticonModel?)
}
class EmoticonCollectionViewCell: UICollectionViewCell {
    
    //设置代理
    weak var delegate: EmoticonCellSelectedDelegate?
    
    //每个cell的大小和collectionView一样大小
    //每个cell使用九宫格布局，放置20个表情，加一个删除按钮
    @IBOutlet weak var label: UILabel!
    
    //表情提示视图
    private lazy var tipView = CPJEmoticonTipView()
    
    //当前界面的表情模型数组
    var emoticonsArray: [CPJEmoticonModel]?
    {
        didSet
        {
            for btn in contentView.subviews
            {
                //隐藏所有按钮
                btn.isHidden = true
            }
            
            //显示删除按钮
            contentView.subviews.last?.isHidden = false
            for (i,emoticonModel) in (emoticonsArray ?? []).enumerated()
            {
                let btn = contentView.subviews[i] as! UIButton
                
                btn.isHidden = false
                
//                if emoticonModel.image != nil
//                {
//                    btn.setImage(emoticonModel.image, for: .normal)
//                }
//                if emoticonModel.emoji != nil
//                {
//                    btn.setTitle(emoticonModel.emoji, for: .normal)
//                }
                //设置按钮图片,如果emoticonModel.image为nil，会清空图片
                btn.setImage(emoticonModel.image, for: .normal)
                //设置按钮文字,如果emoji为nil，会清空文字
                btn.setTitle(emoticonModel.emoji, for: .normal)
            }
        }
    }
    
    //纯代码加载cell，执行该方法
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        //初始化布局
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else
        {
            return
        }
        //将提示视图添加到窗口上
        w.addSubview(tipView)
        
        //隐藏提示按钮
        tipView.isHidden = true
    }
    @objc fileprivate func emoticonButtonSelected(btn: UIButton)
    {
        let tag = btn.tag
        print(tag)
        
        var emoticonModel: CPJEmoticonModel?
        let count = emoticonsArray?.count ?? 0
        
        if tag < count
        {
            //不是删除按钮
            emoticonModel = emoticonsArray?[tag]
        }
        
        delegate?.emoticonCellDidSelected(cell: self, emoticonModel: emoticonModel)
        
    }
    
    @objc fileprivate func longPressGesture(gesture: UILongPressGestureRecognizer)
    {
        print("长按手势")
        
        //addSubview(tipView)
        //获取触摸位置
        let location = gesture.location(in: self)
        
        //获取触摸位置对应的button
        guard let button = buttonWithLocation(location: location) else
        {
            tipView.isHidden = true
            return
        }
        
        //处理手势状态
        switch gesture.state
        {
        case .began, .changed:
            tipView.isHidden = false
            
            //坐标系的转换：将按钮参照cell的坐标系，转换到参照window上
            let center = self.convert(button.center, to: window)
            tipView.center = center
            
            //设置提示按钮表情
            guard let count = emoticonsArray?.count else
            {
                return
            }
            if button.tag < count
            {
                tipView.emoticonModel = emoticonsArray?[button.tag]
            }
            
        case .ended:
            tipView.isHidden = true
            //执行选中按钮的函数
            emoticonButtonSelected(btn: button)
        case .cancelled, .failed:
            tipView.isHidden = true
            
        default:
            break
        }
        print(button)
    }
    
    func buttonWithLocation(location: CGPoint) -> UIButton?
    {
        for btn in contentView.subviews as! [UIButton]
        {
            
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last
            {
                return btn
            }
        }
        return nil
    }
    //xib加载cell，执行该方法
//    override func awakeFromNib() {
//        
//        //初始化布局
//        setupUI()
//    }
}

private extension EmoticonCollectionViewCell
{
    //从xib加载cell，cell 的bounds是xib中给定的大小
    //纯代码创建cell，cell的bounds是布局属性中设置的itemSize大小
    func setupUI()
    {
        //行数
        let rowCount = 3
        //列数
        let colCount = 7
        
        //左间距
        let leftEdge: CGFloat = 8
        
        //底部间距
        let bottomEdge: CGFloat = 16
        
        
        //宽度
        let width = (bounds.width - 2 * leftEdge)/CGFloat(colCount)
        //高度
        let height = (bounds.height - bottomEdge)/CGFloat(rowCount)
        
        for i in 0..<21
        {
            let btn = UIButton()
            
            let row = i / colCount
            let col = i % colCount
            
            let x = leftEdge + width * CGFloat(col)
            let y =  height * CGFloat(row)
            
            btn.frame = CGRect(x: x, y: y, width: width, height: height)
            
            //设置字体大小
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
          
            //设置按钮tag
            btn.tag = i
            
            //添加按钮监听方法
            btn.addTarget(self, action: #selector(emoticonButtonSelected), for: .touchUpInside)
            contentView.addSubview(btn)
        }
        
        //删除按钮
        let removeBtn = contentView.subviews.last as! UIButton
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: EmotionManager.shared.bundle, compatibleWith: nil)
        removeBtn.setImage(image, for: .normal)
        
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
        
    }
}
